<script>
import { defineComponent, reactive, toRaw } from 'vue'
import MakeForm, { MakeFormState } from '@Components/makeForm'
import DataTable from '@Components/dataTable'
import {
  authRoleList,
  authRoleAdd,
  authRoleDel,
  authRolePermissionAdd,
} from '@Config/server/api'
import { message } from 'ant-design-vue'
import { createPagination, Messages, confirm } from '@Config/config'
import { useRoute, useRouter } from 'vue-router'
import { useUrl, transform_pre_fn } from '@Hooks/url'
import { useWin } from '@Hooks/win'
import RoleForm from '@Page/role/components/roleForm'
import SetRoleForm from '@Page/role/components/setRoleForm'
import { cloneDeep, findIndex, uniqueId } from 'lodash'
export default defineComponent({
  components: {
    DataTable,
    MakeForm,
    RoleForm,
    SetRoleForm,
  },
  setup(props, context) {
    let tableData = reactive({
      data: {
        source: [],
        columns: [
          {
            key: 'roleName',
            dataIndex: 'roleName',
            title: '角色名称',
            width: '30%',
          },
          {
            key: 'description',
            dataIndex: 'description',
            title: '角色描述',
            width: '40%',
          },
          {
            key: 'operation',
            dataIndex: 'operation',
            title: '操作',
            width: '20%',
          },
        ],
      },
    })

    let custom = [
      {
        key: 'operation',
        bodyFn: (text, record, index) => {
          return (
            <a-space>
              <a-button
                type="primary"
                loading={record.local_loading}
                onClick={setPowerHandler.bind(null, text, record, index)}
              >
                权限配置
              </a-button>
            </a-space>
          )
        },
      },
    ]
    let route = useRoute()
    let router = useRouter()

    let searchData = async () => {
      fromStateToQuery({
        path: route.path,
      })
    }
    //分布配置
    let pagination = reactive({
      data: createPagination(searchData, true, false),
    })
    //切换分页
    // pagination.data.onChange = (pageNumber, pageSize) => {
    //   pagination.data.current = pageNumber
    //   pagination.data.pageSize = pageSize
    //   searchData()
    // }

    let form_state = reactive({ data: null })
    let loading = reactive({ search_loading: false })

    let { fromStateToQuery } = useUrl({
      fn: async () => {
        loading.search_loading = true
        let _params = {
          size: pagination.data.pageSize,
          index: pagination.data.current,
          ...form_state.data,
        }
        let _result = await authRoleList(_params)
        loading.search_loading = false
        if (_result.code != 0) {
          Messages.add(message.error(`获取数据发生错误[${_result.msg}]`))
          return
        }
        tableData.data.source = _result.data?.records
        pagination.data.total = _result.data?.total
        pagination.data.current = _result.data?.index
        pagination.data.pageSize = _result.data?.size
      },
      formState: [],
    })

    //设置角色列表
    let [roleForm] = useWin({
      component: (
        <RoleForm
          onResult={async ({ params, innerCallBack }) => {
            let _params = { id: 0, ...params }

            let _result = await authRoleAdd(_params)
            if (_result.code == 0) {
              Messages.add(message.success('操作成功'))
              if (_params.id == 0) {
                tableData.data.source.unshift(_result.data)
              } else {
                let _index = findIndex(tableData.data.source, {
                  id: _result.data.id,
                })
                if (_index >= 0) {
                  tableData.data.source.splice(_index, 1, _result.data)
                }
              }
            } else {
              Messages.add(message.error(`新增失败[${_result.msg}]`))
            }
            innerCallBack(_result)
          }}
        />
      ),
      attr: {
        title: '角色',
      },
    })
    //设置权限列表
    let [setRoleForm] = useWin({
      component: (
        <SetRoleForm
          onResult={async ({ powerList, record, innerCallBack }) => {
            let _index = findIndex(tableData.data.source, { id: record.id })
            let _result = await authRolePermissionAdd({
              permissionIdList: powerList.map((x) => x.id),
              roleId: record.id,
            })
            if (_result.code == 0) {
              Messages.add(message.success('设置成功'))

              let newItem = cloneDeep({
                ...toRaw(tableData.data.source[_index]),
                rolePermissionList: powerList.map((x) => {
                  return {
                    id: uniqueId('local_'),
                    permissionId: x.tag,
                    permissionName: x.label,
                  }
                }),
              })

              tableData.data.source.splice(_index, 1, newItem)
            } else {
              Messages.add(message.error(`设置失败[${_result.msg}]`))
            }
            innerCallBack(_result)
          }}
        />
      ),
      attr: { title: '设置权限' },
    })

    let createRoleHandler = () => {
      roleForm({
        params: {},
      })
    }

    let setPowerHandler = (text, record, index) => {
      setRoleForm({
        params: {
          record: record,
        },
      })
    }

    return { tableData, pagination, loading, custom, createRoleHandler }
  },
  render() {
    return (
      <>
        <a-row>
          <a-col span={24}>
            <DataTable
              data={this.tableData}
              uiAttr={{
                scroll: { x: null },
                tableLayout: 'fixed',
                bordered: true,
              }}
              custom={this.custom}
              loading={this.loading}
            >
       
            </DataTable>
          </a-col>
        </a-row>

        <a-affix {...this.pagination_affix_attr()}>
          <div class="affix">
            <a-pagination {...this.pagination.data} />
          </div>
        </a-affix>
      </>
    )
  },
})
</script>
